import uuid
from flaskapp.model.mongo import db
# from flaskapp.model.db import db, Alarm
# from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime
import logging
from bson import ObjectId
# Setup logging
logger = logging.getLogger(__name__)

def alarm_insert(box: dict, classType: str, conf: float, fp: str, target: str, mediaID: str) -> bool:
    try:
        current_datetime = datetime.now()
        # alarm = Alarm(id=str(uuid.uuid4()), box=box, classType=classType, confidence=conf, file_path=fp, target=target, mediaID=mediaID, timestamp=current_datetime)
        # db.session.add(alarm)
        # db.session.commit()
        alarm = {"box":box, "classType":classType, "confidence":conf, "file_path":fp, "target":target, "mediaID":mediaID, "timestamp":current_datetime}
        ret=db.alarm.insert_one(alarm)
        logger.info(f"Inserted alarm with id: {ret.inserted_id}")
        return True
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error inserting alarm: {e}")
        return False

def alarm_delete(alarm_id: str) -> bool:
    try:
        # alarm = Alarm.query.get(alarm_id)
        alarm = db.alarm.find_one({"_id":ObjectId(alarm_id)})
        if alarm:
            # db.session.delete(alarm)
            # db.session.commit()
            ret=db.alarm.delete_one({"_id":ObjectId(alarm_id)})
            logger.info(f"Deleted alarm with id: {ret.deleted_count}")
            return True
        logger.warning(f"Alarm with id: {alarm_id} not found")
        return False
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error deleting alarm: {e}")
        return False

def alarm_get(page: int = 1, per_page: int = 10, classType: str = None) -> dict:
    try:
        logger.info(f"Fetching alarms for page: {page}, per_page: {per_page}, classType: {classType}")
        # query = Alarm.query.order_by(Alarm.timestamp.desc())
        # if classType and classType.upper() == "ALL":
        #     # 如果 classType 是 "all" 或者 "ALL"，则不添加过滤条件，返回所有记录
        #     pass
        # elif classType:
        #     # 否则，根据指定的 classType 进行过滤
        #     query = query.filter(Alarm.classType == classType)
        # pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        # alarms = [alarm.to_dict() for alarm in pagination.items]
        
        condition={}
        if classType and classType.upper() == "ALL":
            pass
        elif classType:
            condition["classType"]=classType
        total=db.alarm.count_documents(condition)
        page=db.alarm.find(condition).sort("timestamp").limit(per_page).skip(per_page*(page-1))
        items=[]
        for r in page:
            items.append(r)
            
        logger.info(f"Retrieved {len(items)} alarms from page {page}, total items: {total}")
        return {
            "alarms": items,
            "total": total
        }
    except BaseException as e:
        logger.error(f"Error retrieving alarms: {e}")
        return {"alarms": [], "total_pages": 0, "current_page": 0, "total_items": 0}



